<template>
  <view class="chat-container">
    <!-- 标题栏 -->
    <view class="chat-header">
      <text>蜗牛Ai智能助手</text>
    </view>
    
    <!-- 聊天内容区域 -->
    <scroll-view class="chat-messages" scroll-y="true" scroll-with-animation>
      <view v-for="(item, index) in messages" :key="index" class="message-item" :class="item.role">
        <view class="message-content">
          <text>{{item.content}}</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入框区域 -->
    <view class="input-area">
      <input 
        class="input-box" 
        v-model="inputMessage" 
        placeholder="请输入您的问题..." 
        @confirm="sendMessage"
      />
      <button class="send-btn" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'

const inputMessage = ref('')
const messages = ref([
  { role: 'assistant', content: '您好！我是蜗牛AI助手，有什么可以帮您的吗？' }
])

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: inputMessage.value
  })
  
  const userMessage = inputMessage.value
  inputMessage.value = '' // 清空输入框
  
  try {
    // 发送请求到后端
    const res = await uni.request({
      url: 'http://127.0.0.1:8081/ai/chat',
      method: 'POST',
      data: {
        message: userMessage
      },
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    // 添加AI回复
    messages.value.push({
      role: 'assistant',
      // content: res.data.response || '收到回复但内容为空'
	  content: res.data || '收到回复但内容为空'
    })
    
  } catch (error) {
    console.error('请求出错:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，请求服务出错，请稍后再试'
    })
  }
  
  // 滚动到底部
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 99999,
      duration: 300
    })
  }, 100)
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
}

.chat-header {
  text-align: center;
  padding: 15px 0;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 1px solid #eee;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.message-item {
  margin-bottom: 15px;
}

.message-item.user {
  display: flex;
  justify-content: flex-end;
}

.message-item.assistant {
  display: flex;
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 5px;
  word-break: break-word;
}

.user .message-content {
  background-color: #95ec69;
  color: #000;
}

.assistant .message-content {
  background-color: #f0f0f0;
  color: #333;
}

.input-area {
  display: flex;
  padding: 10px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.input-box {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
}

.send-btn {
  padding: 0 20px;
  background-color: #07c160;
  color: white;
  border-radius: 5px;
}
</style>